package com.example.bttrace;

import java.util.StringTokenizer;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class SettingsActivity extends ActionBarActivity {
	private EditText iptext1;
	private EditText iptext2;
	private EditText iptext3;
	private EditText iptext4;
	private EditText porttext;
	private RadioButton radioStart;
	private RadioButton radioCheck1;
	private RadioButton radioCheck2;
	private RadioButton radioEnd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_settings);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		
		SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_settings), Context.MODE_PRIVATE);
		int port = sharedPref.getInt(getString(R.string.saved_port), Settings.DEFAULT_PORT);
		int checkPoint = sharedPref.getInt(getString(R.string.saved_checkpoint), Settings.DEFAULT_CHECKPOINT);
		String server = sharedPref.getString(getString(R.string.saved_ip), Settings.DEFAULT_IP);
		
		StringTokenizer token = new StringTokenizer(server,".");
		
		iptext1 = (EditText) findViewById(R.id.ipText1);
		iptext1.setText(token.nextToken()+"");
		iptext1.addTextChangedListener(new IPTextWatcher());
		
		iptext2 = (EditText) findViewById(R.id.ipText2);
		iptext2.setText(token.nextToken()+"");
		iptext2.addTextChangedListener(new IPTextWatcher());
		
		iptext3 = (EditText) findViewById(R.id.ipText3);
		iptext3.setText(token.nextToken()+"");
		iptext3.addTextChangedListener(new IPTextWatcher());
		
		iptext4 = (EditText) findViewById(R.id.ipText4);
		iptext4.setText(token.nextToken()+"");
		iptext4.addTextChangedListener(new IPTextWatcher());
		
		porttext = (EditText) findViewById(R.id.portText);
		porttext.setHint(Settings.MINPORT+" - "+Settings.MAXPORT);
		porttext.setText(port+"");
		porttext.addTextChangedListener(new PortTextWatcher());
		
		radioStart = (RadioButton) findViewById(R.id.radioStart);
		radioStart.setText(Settings.CHECKPOINTS[0]);
		
		radioCheck1 = (RadioButton) findViewById(R.id.radioCheck1);
		radioCheck1.setText(Settings.CHECKPOINTS[1]);
		
		radioCheck2 = (RadioButton) findViewById(R.id.radioCheck2);
		radioCheck2.setText(Settings.CHECKPOINTS[2]);
		
		radioEnd = (RadioButton) findViewById(R.id.radioEnd);
		radioEnd.setText(Settings.CHECKPOINTS[3]);
		
		switch (checkPoint){
			case 1: radioCheck1.setChecked(true); break;
			case 2: radioCheck2.setChecked(true); break;
			case 3: radioEnd.setChecked(true); break;
			default: radioStart.setChecked(true);
		}
	}
	
	private boolean validateAndSave (){
		String ip = iptext1.getText()+"."+iptext2.getText()+"."+iptext3.getText()+"."+iptext4.getText();
		int port,checkPoint;
		
		if (!Settings.validIP(ip))
			return false;
		
		try {
			port = Integer.parseInt(porttext.getText().toString());
			if(!Settings.validPort(port))
				return false;
		}
		catch (NumberFormatException ex){
			return false;
		}
		
		if (radioStart.isChecked())
			checkPoint = 0;
		else if (radioCheck1.isChecked())
			checkPoint = 1;
		else if (radioCheck2.isChecked())
			checkPoint = 2;
		else
			checkPoint = 3;
		
		SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_settings), Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPref.edit();
		editor.putInt(getString(R.string.saved_checkpoint), checkPoint);
		editor.putInt(getString(R.string.saved_port), port);
		editor.putString(getString(R.string.saved_ip), ip);
		editor.commit();
		
		return true;
	}
	
    public void onPause (){
    	super.onPause();
    	
    	if (validateAndSave()) {
    		Toast toast = Toast.makeText(getApplicationContext(), "Settings Saved", Toast.LENGTH_SHORT);
    		toast.show();
    	}
    	
    	else {
    		Toast toast = Toast.makeText(getApplicationContext(), "Wrong values. Not saved", Toast.LENGTH_SHORT);
    		toast.show();
    	}
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.settings, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private class IPTextWatcher implements TextWatcher {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
        	try {
        	     int val = Integer.parseInt(s.toString());
        	     if(val > 255) {
        	        s.replace(0, s.length(), "255", 0, 3);
        	     } 
        	} catch (NumberFormatException ex) {}
        }
    }
	
	private class PortTextWatcher implements TextWatcher {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
        	try {
        	     int val = Integer.parseInt(s.toString());
        	     if(val > Settings.MAXPORT) {
        	        s.replace(0, s.length(), ""+Settings.MAXPORT, 0, 5);
        	     } 
        	} catch (NumberFormatException ex) {}
        }
    }
}
